# -*- coding: utf-8 -*-
import urllib
import urllib2
import re
import xmlrpclib
import os

def reg(reg,html):
    p = re.compile(reg)
    return p.findall(html)

def main(key):
	key = urllib.quote('%s'%key.decode('utf-8').encode('GBK'))
	url = 'http://search.you.video.sina.com.cn/s?%s'
	values = {
	            'key'  : key,
	            'type' : 'video',
	            'sort' : 'click',
	        }
	data = urllib.urlencode(values)
	fullurl = url%(data.decode('utf8'))
	response = urllib2.urlopen(fullurl)
	html = response.read()
	html = html.decode('GBK')
	vid = r'vid=(\d+)'
	vidList = reg(vid,html)
	info = r'<li class="bk.*"><a href="(.*)" target="_blank"><img src="(.*)" alt=".*" title=".*" border=".*" /></a></li>'
	infolist = reg(info,html)
	all = zip(infolist,vidList)
	play_dic = {}
	for a in all:
	    play_info = {}
	    play_info['flvname'] = ''
	    play_info['flvsrc'] =''
	    play_info['flvurl'] = a[0][0]
	    play_info['flvimg'] = a[0][1]
	    play_info['vid'] = a[1]
	    play_dic['%s'%a[1]] = play_info
	play_dic = downList(play_dic)
	return play_dic

def downList(play_dic):
    downlist = []
    downlistName = []
    url = 'http://v.iask.com/v_play.php?vid=%s'
    for key,value in play_dic.items():
    #for vid in play_dic:
        full_url = url%key
        response = urllib2.urlopen(full_url)
    	html = response.read()
    	html = html.decode('utf-8')
        flv = r'http.*flv'
        flvList = reg(flv,html)
        if len(flvList) == 0:
            del(play_dic['%s'%key])
            continue
        play_dic['%s'%key]['flvsrc'] = flvList[0]
        name = r'<vname><\!\[CDATA\[(.*)\]\]><\/vname>'
        nameList = reg(name,html)
        play_dic['%s'%key]['flvname'] = nameList[0]
    return play_dic

def index(request):
    alllist = []
    key = ''
    if request.method == 'POST':
        key = request.POST['key']
        if not (key == '' or key == None):
            alllist = main(key)
    return render_to_response('yaoflv_templates/index.html',{'all':alllist,'key':key})

if __name__ == '__main__':
    key = '圣斗士 极乐净土'
    alllist = main(key)
    rpc_srv = xmlrpclib.ServerProxy("http://junyw01.host921.londit.cn/yaoflv/flvrpc/")
    result = rpc_srv.multiply(key,alllist,'wglin122')